use sdl2::TimerSubsystem;

pub struct FpsDeltaTime {
    pub frame_delay: u32, // Frame delay in milliseconds
    pub dt: f32,          // Delta time in seconds
    pub last_time: u64,
    timer_subsystem: TimerSubsystem,
}

impl FpsDeltaTime {
    pub fn new(fps_cap: u32, timer_subsystem: TimerSubsystem) -> Self {
        Self {
            last_time: timer_subsystem.performance_counter(),
            timer_subsystem,
            frame_delay: 1000 / fps_cap,
            dt: 0.0,
        }
    }

    pub fn frame_start(&mut self) {
        let now = self.timer_subsystem.performance_counter();
        let elapsed = now - self.last_time;
        self.dt = elapsed as f32 / self.timer_subsystem.performance_frequency() as f32;
        self.last_time = now;
    }

    pub fn frame_end(&self) {
        let now = self.timer_subsystem.performance_counter();
        let elapsed = now - self.last_time;
        let cap_frame_end = (((elapsed as f32) * 1000.0)
            / (self.timer_subsystem.performance_frequency() as f32))
            as u32;

        if cap_frame_end < self.frame_delay {
            self.timer_subsystem.delay(self.frame_delay - cap_frame_end);
        }
    }
}
